package com.dragon.concurrent.demo.immutable;

public class ImmutablePerformance {

    public static void main(String[] args) throws InterruptedException {
        // 25068 Sync 101833
        // 26792 Immutable 78989
        long startTimeStamp = System.currentTimeMillis();
        SyncObj syncObj = new SyncObj();
        syncObj.setName("dragon");
//        for (int i = 0; i < 10000000; i++) {
//            System.out.println(Thread.currentThread().getName() + " = " + syncObj.toString());
//        }
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000000; i++) {
                System.out.println(Thread.currentThread().getName() + " = " + syncObj.toString());
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000000; i++) {
                System.out.println(Thread.currentThread().getName() + " = " + syncObj.toString());
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        long endTimeStamp = System.currentTimeMillis();
        System.out.println("speed time :" + (endTimeStamp - startTimeStamp));
    }
}

final class ImmutableObj {

    private final String name;

    public ImmutableObj(String name) {
        this.name = name;
    }

    public String toString() {
        return "name [" + this.name + " ]";
    }
}

class SyncObj {

    private String name;

    public synchronized void setName(String name) {
        this.name = name;
    }

    public synchronized String toString() {
        return "name [" + this.name + " ]";
    }
}
